package com.example.teach.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.teach.entity.Result;
import com.example.teach.entity.User;
import com.example.teach.exception.ServiceException;
import com.example.teach.mapper.UserMapper;
import com.example.teach.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public void add(User user) {
        //User u = getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()));
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,user.getUserName());
        if(userMapper.selectOne(wrapper) != null){
            throw new ServiceException("用户已存在");
        }

        String password = passwordEncoder.encode(user.getPassWord());
        user.setPassWord(password);
        userMapper.insert(user);

    }

    @Override
    public User login(User user) {
        //ser u = getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, user.getUserName()).eq(User::getPassWord, user.getPassWord()));
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName,user.getUserName());
        User u = userMapper.selectOne(wrapper);

        if(u != null && passwordEncoder.matches(user.getPassWord(),u.getPassWord())){
            return u;
        }
        return null;
    }

    @Override
    public boolean selectOne(String userName) {
        if(userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName,userName)) != null){
            return true;
        }
        return false;
    }

    @Override
    public User getByteacherId(Integer teacherId) {
        return userMapper.selectByteacherId(teacherId);
    }

    @Override
    public Result selectId(Integer userId) {
        return Result.success(userMapper.selectId(userId));
    }


}
